const http = require('http');
const fs = require('fs');
const { YOLO } = require('./yolo');

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.setHeader('Access-Control-Allow-Origin', '*');

  //打印请求头

  //在被请求的网站上，设置HTTP头，添加"Access-Control-Allow-Origin:*" //值为*或指定的域名。


  //node httpserver.js        
  // req.on('data', (chunk) => {
  //   console.log('Received chunk: ', chunk.toString());
  // });
  //处理post请求
  if (req.method === 'POST') {
    console.log('POST request received');
    let body = ''; // 初始化body变量
    req.on('data', (chunk) => {
      console.log('Received chunk: ', chunk.toString().length);
      //将buffer转为json
      body += chunk.toString();
    });
    req.on('end', async () => {
      let data = JSON.parse(body);
      //将接收的base64数据转图片
      fs.writeFile('received.jpg', data.image.split(';base64,')[1], 'base64', (err) => {
        if (err) throw err;
        console.log('Image saved!');
        // 在图片保存后调用YOLO
        YOLO('received.jpg')
          .then(yolo => {
            //等待yolo处理完成，将图片转为base64数据返回给客户端
            fs.readFile('results_received.jpg', 'base64', (err, resultData) => {
              if (err) throw err;
              console.log('Sending result');
              res.end(JSON.stringify({ result: 'data:image/png;base64,' + resultData, inference_results: yolo }));
            });
          })
          .catch(error => {
            console.error('YOLO error:', error);
            res.end(JSON.stringify({ result: 'error', inference_results: error }));
          });
      });
      console.log('End');
    });
  }

});

server.on('connection', (socket) => {
  console.log('New connection');
});

server.listen(4000, () => {
  console.log('Server running at http://localhost:4000/');
});